<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 09/10/2017
 * Time: 12:41
 */
namespace backend\controllers;

use common\models\ar\MoneyRecharge;
use common\models\ar\UserMoney;
use common\models\ar\UserBrokers;
use common\models\RechargeDaos;
use common\models\ar\User;
use common\models\ar\ExchangeRate;
use common\models\ar\UserMoneyChangerecord;
use common\models\ar\ChangeCache;
class RechargesController extends BackendController
{
    public function actionLists()
    {
        $req = \Yii::$app->request;
        $isRender = $req->get('isRender', 1);//1为搜索页面，2为异步获取代理记录
        $uid = \Yii::$app->user->identity->id;
        $userModel = UserBrokers::findOne($uid);
        $status = (int)$req->get('status', -1);
//        $clientSN = trim($req->get('clientSN', ''));
        $pClientSN = trim($req->get('p_clientSN', ''));
        $pageNo = (int)$req->get('pageNo', 1);
        $pageSize = \Yii::$app->params['pageSize'];
        //日期
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;
        $uid = -1;
//        if ($clientSN != '') {
//            $where['clientSN'] = $clientSN;
//            $where['uid_level_' . $userModel->level] = $userModel->uid;
//            $tmp = UserTrade::find()->where($where)->one();
//            if (!$tmp) {
//                $uid = 0;
//            } else {
//                $uid = $tmp->uid;
//            }
//        }

        if ($pClientSN) {
            $where = [];
            $where['userID'] = $pClientSN;
            if (!empty($where)) {
                $tmp = User::find()->where($where)->one();
                if (!$tmp) {
                    $uid = 0;
                } else {
                    $uid = $tmp->userID;
                }
            }
        }

        //直接返回
        if ($uid == 0) {
            $return = [
                'pageNo' => $pageNo,
                'pageTotal' => 0,
                'sumMoney' => 0,
                'lists' => [],
            ];
        } else {
            $res = RechargeDaos::history(
                $status,
                $uid,
                $from,
                $to,
                $pageNo,
                $pageSize
            );

            $return = [
                'pageNo' => $pageNo,
                'pageTotal' => ceil($res['total'] / $pageSize),
                'sumMoney' => $res['sumMoney'],
                'lists' => $res['lists'],
            ];
        }

        if ($isRender == 1) {
            $return['from'] = $from;
            $return['to'] = $to - 1;

            return $this->renderPartial('lists', $return);
        } else {
            exit(json_encode($return));
        }
    }

    public function actionCancel(){
        $req = \Yii::$app->request;
        $rmb=ExchangeRate::findone(['currency'=>'RMB']);
        $recharge_sn=$req->get('recharge_sn');
        $all=MoneyRecharge::findOne(['recharge_sn'=>$recharge_sn]);
        $str="remark=%E6%8E%88%E4%BA%88%2Cfrompartyid%3Anull%2Cfromaccountnumber%3A990305001001&subject=%E5%85%85%E5%80%BC&transactiondate=2018-09-14%2011%3A14%3A31&billamount=0.01&terminal=PC&businessrecordnumber=1418091411140250001&backurl=http%3A%2F%2F106.14.148.41%3A8090%2Fpay-return%2Findex&fromaccountnumber=990305001001&inputdate=2018-09-14%2011%3A14%3A02&transactiontype=%E6%B6%88%E8%B4%B9&transactionamount=0.01&topartyid=10226743&fronturl=http%3A%2F%2F106.14.148.41%3A8090%2Fmoneys%2Frecharge-return&toaccountnumber=8800010248461&transactionnumber=1618091411143150001&status=%E6%88%90%E5%8A%9F&businesstype=%E4%BA%92%E8%81%94%E7%BD%91%E9%87%91%E8%9E%8D&businessnumber=".$recharge_sn."&tf_sign=12AC79272A0CBA8BD428A246B0234DDB&updatedate=2018-09-14%2011%3A14%3A31&appid=1994001";
        $time = time();
            if (empty($all->data_response)) {
                $transaction= \Yii::$app->db->beginTransaction();
                try{
                    $all->status = 2; // 支付成功
                    $all->pay_end_time = $time;
                    $all->data_response = json_encode($str);
                    $all->save();
                        $Tmoney=$all->money;
                        //$Tmoney=($Tmoney-$Tmoney*0.005);
                        $Hmoney=($Tmoney-$Tmoney*0.006)/$rmb['exchange_rate'];
                        $Zmoney=UserMoney::findone(['userID'=>$all->userID]);
                        $a=(float)($Zmoney->totalMoney);
                        $c=(float)($Zmoney->userDeposit);
                        $b=(float)$Hmoney;
                        $b=sprintf("%.2f",substr(sprintf("%.3f",$b), 0,-1));
                        $money=$a+$b;
                        $userMoney=$c+$b;
                        $Zmoney->totalMoney=$money;
                        $Zmoney->userDeposit=$userMoney;
                        $Money_Record = new UserMoneyChangerecord;
                        $Money_Record->userID=$all->userID;
                        $Money_Record->changeMoney=$b;
                        $Money_Record->changeDesc="入劣后:三方支付";
                        $Money_Record->changeTime=Date('Y-m-d H:i:s');
                        $Money_Record->type=1;
                        $Money_Record->tradeId=0;
                        $Money_Record->preTotalMoeny=$Zmoney['totalMoney'];
                        $Money_Record->preTotalMoney=$Zmoney['totalMoney'];
                        $Money_Record->preequip=$Zmoney['equip'];
                        $Money_Record->save();
                        $Zmoney->save();
                        $sql="SELECT id FROM `user_money_changerecord` WHERE 
                  changeTime=(SELECT MAX(changeTime) FROM `user_money_changerecord` WHERE `userID`={$all->userID})";
                        $extra_id=$Money_Record::findBySql($sql)->all();
                        $Change_Record = new ChangeCache;
                        $Change_Record->userid=$all->userID;
                        $Change_Record->change_type=2;
                        $Change_Record->extra_id=$extra_id;
                        $Change_Record->save();
                        $transaction->commit();//提交事务
                    $code = 1;
                    $msg = "操作成功";
                }
                catch (Exception $e){
                    $transaction->rollback();//回滚事务
                }
        }else{
            $code = 0;
            $msg = "操作失败,或本笔充值已确认！";
        }
        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }
}